import * as pdfjsLib from 'pdfjs-dist/build/pdf.js';
import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.js';
// npm i pdfjs-dist@2.2.228

export async function loadPDF(url) {
    let images = undefined;
    let pageCount = 0;
    var mergedCanvas = document.createElement('canvas');
    var ctxMerged = mergedCanvas.getContext('2d');
    try {
        const loadingTask = pdfjsLib.getDocument(url); // 加载pdf
        const pdf = await loadingTask.promise; // 获取pdf
        pageCount = pdf.numPages; // 获取pdf页数

        // 循环处理每一页
        for (let pageNum = 1; pageNum <= pageCount; pageNum++) {
            const page = await pdf.getPage(pageNum); //  获取pdf页
            const viewport = page.getViewport({ scale: 1 }); // 获取pdf页的视口
            const canvas = document.createElement('canvas'); // 创建canvas
            const context = canvas.getContext('2d'); // 获取canvas的2d上下文
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            if (pageNum == 1) {
                mergedCanvas.height = viewport.height * pageCount;
                mergedCanvas.width = viewport.width;
            }
            const renderContext = {
                canvasContext: context,
                viewport: viewport
            };
            await page.render(renderContext).promise; // 渲染pdf页到canvas
            ctxMerged.drawImage(canvas, 0, viewport.height * (pageNum - 1)); // 合并多个canvas
        }

        images = mergedCanvas.toDataURL('image/png');
    } catch (error) {
    } finally {
        return images;
    }
}
